package com.se.xb.controller;

import com.alibaba.fastjson.JSON;
import com.se.xb.entity.Article;
import com.se.xb.entity.User;
import com.se.xb.entity.dto.*;
import com.se.xb.service.ArticleService;
import com.se.xb.service.UserService;
import org.springframework.beans.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@WebServlet("/article/*")
public class ArticleServlet extends BaseServlet {

    ArticleService articleService = new ArticleService();

    UserService userService = new UserService();



    public void getArticleList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        User user = (User) request.getSession().getAttribute("user");
        SearchDto<String> objectSearchDto = new SearchDto<>(new ArrayList<>(), 1);
        objectSearchDto.setCurrentPage(Integer.valueOf(request.getParameter("page")));
        ArrayList<String> queryList = objectSearchDto.getQueryList();
        queryList.add(String.valueOf(user.getId()));
        queryList.add(request.getParameter("title"));
        PageResult<Article> articleList = articleService.getArticleList(objectSearchDto);
        List<Article> records = articleList.getRecords();
        List<ArticleDto> favorite = articleService.getFavoriteList(records, user.getId());
        PageResult<ArticleDto> objectPageResult = new PageResult<>();
        objectPageResult.setRecords(favorite);
        objectPageResult.setPage(articleList.getPage());
        objectPageResult.setTotal(articleList.getTotal());
        objectPageResult.setTotalPage(articleList.getTotalPage());
        objectPageResult.setPageSize(articleList.getPageSize());
        if (articleList != null) {
            response.getWriter().write(JSON.toJSONString(Result.success(objectPageResult)));
        } else {
            response.getWriter().write(JSON.toJSONString(Result.error("获取文章列表失败")));
        }
    }

    public void getFavoriteList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        User user = (User) request.getSession().getAttribute("user");
        SearchDto<String> objectSearchDto = new SearchDto<>(new ArrayList<>(), 1);
        objectSearchDto.setCurrentPage(Integer.valueOf(request.getParameter("page")));
        ArrayList<String> queryList = objectSearchDto.getQueryList();
        queryList.add(String.valueOf(user.getId()));
        queryList.add(request.getParameter("title"));
        PageResult<Article> articleList = articleService.getFavoriteList(objectSearchDto);
        List<Article> records = articleList.getRecords();
        List<ArticleDto> favorite = articleService.getFavoriteList(records, user.getId());
        PageResult<ArticleDto> objectPageResult = new PageResult<>();
        objectPageResult.setRecords(favorite);
        objectPageResult.setPage(articleList.getPage());
        objectPageResult.setTotal(articleList.getTotal());
        objectPageResult.setTotalPage(articleList.getTotalPage());
        objectPageResult.setPageSize(articleList.getPageSize());
        if (articleList != null) {
            response.getWriter().write(JSON.toJSONString(Result.success(objectPageResult)));
        } else {
            response.getWriter().write(JSON.toJSONString(Result.error("获取文章列表失败")));
        }
    }

    /**
     * 获取文章信息，包括用户关注列表和文章是否被用户收藏
     *
     * @param request HTTP请求对象，用于获取用户会话和请求参数
     * @param response HTTP响应对象，用于向客户端返回数据
     * @throws ServletException 如果Servlet操作失败
     * @throws IOException 如果输入输出操作失败
     * @throws SQLException 如果数据库操作失败
     */
    public void getArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        // 获取当前会话中的用户信息
        User user = (User) request.getSession().getAttribute("user");
        // 获取用户关注的用户列表
        List<User> focusList = userService.getFocusList(user.getId());

        // 从请求参数中获取文章ID
        Long id = Long.parseLong(request.getParameter("id"));
        // 根据ID获取文章信息
        Article article = articleService.getArticle(id);
        // 获取文章的收藏信息
        ArticleDto favorite = articleService.getFavorite(article);
        // 创建ArticleUserDto对象，用于封装文章和用户收藏信息
        ArticleUserDto articleUserDto = new ArticleUserDto();
        // 初始化收藏关注用户列表
        List<User> favoriteFocusList = articleUserDto.getFavoriteFocusList();
        favoriteFocusList=new ArrayList<>();
        // 将收藏信息复制到ArticleUserDto对象中
        BeanUtils.copyProperties(favorite, articleUserDto);

        // 获取当前文章的收藏列表
        List<Article> currentFavoriteArticleList = articleService.getFavoriteList(user.getId());
        // 判断当前文章是否被用户收藏
        if (currentFavoriteArticleList.contains(article)){
            articleUserDto.setIsFavorite(true);
        }

        // 遍历用户关注列表，查找收藏了当前文章的用户
        for (User user1 :focusList) {
            List<Article> favoriteList = articleService.getFavoriteList(user1.getId());
            if (favoriteList.contains(article)){
                favoriteFocusList.add(user1);
            }
        }
        // 设置收藏了当前文章的关注用户列表
        articleUserDto.setFavoriteFocusList(favoriteFocusList);

        // 如果文章不存在，返回错误信息
        if (article == null) {
            response.getWriter().write(JSON.toJSONString(Result.error("文章不存在")));
            return;
        }
        // 返回文章和用户收藏信息
        response.getWriter().write(JSON.toJSONString(Result.success(articleUserDto)));
    }


    public void updateBrowseCount(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        Long id = Long.parseLong(request.getParameter("id"));
        Article article = articleService.getArticle(id);
        if (article == null) {
            response.getWriter().write(JSON.toJSONString(Result.error("文章不存在")));
            return;
        }
        article.setBrowseCount(article.getBrowseCount() + 1);
        articleService.updateArticle(article);
        response.getWriter().write(JSON.toJSONString(Result.success()));
    }

    public void addArticle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,
    SQLException {
        User user = (User) request.getSession().getAttribute("user");
        Article article = new Article();
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());
        article.setBrowseCount(Long.parseLong("1"));
        article.setPublishRealName(user.getRealName());
        article.setPublishDate(new Date());
        articleService.addArticle(article);
        response.getWriter().write(JSON.toJSONString(Result.success()));
    }


    public void favorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        User user = (User) request.getSession().getAttribute("user");
        String articleId = request.getParameter("articleId");
        articleService.favorite(user.getId(), Long.parseLong(articleId));
        response.getWriter().write(JSON.toJSONString(Result.success()));
    }

    public void unfavorite(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        User user = (User) request.getSession().getAttribute("user");
        String articleId = request.getParameter("articleId");
        articleService.unfavorite(user.getId(), Long.parseLong(articleId));
        response.getWriter().write(JSON.toJSONString(Result.success()));
    }
}
